// 超全局变量
global._ = require('lodash')
global.moment = require('moment')
global.APP_PATH = process.cwd()
global.path = require('path')
global.fs = require('fs')
global.configure = require('little-man-config')
global.log4js = require('../../framework/lib/log4js')
global.helper = require('../../framework/lib/helper')

// 载入app配置文件
const chalk = require('chalk');

const upstreamService = require('../../service/common/kong/upstream')

// 载入api-free 核心组件
const apiFree = require('api-free')

global.M = apiFree.M
global.DB = apiFree.DB
global.dbUtil = apiFree.dbUtil

// 遍历sys_app表，向kong 同步消费者
async function scan (args = {}) {
    let services_upstream = await upstreamService.list();
    services_upstream = services_upstream.data || [];
    // 查找消费者
    for(let i=0;i<services_upstream.length;i++) {
        let item = services_upstream[i];
        await _scanItem(item)
    }

    return true;
}

async function _scanItem (item = {}) {
    let _check_ret = await upstreamService.health(item.name);
    let _targets = _.get(_check_ret,'data', []);
    log4js.debug('服务名称:', item.name);
    for(let i=0; i<_targets.length; i++) {
        log4js.debug('target:', _targets[i].target, 'weight:', _targets[i].weight, '健康状态:', _targets[i].health === 'HEALTHY' ? chalk.green(_targets[i].health) : chalk.red(_targets[i].health))
    }
}

// 初始化 api-free
apiFree.init(configure.get('apifree')).then(async ()=>{
    await scan();
    log4js.debug('DONE')
    process.exit(0);
}).catch(err => {
    log4js.error(err)
})






